﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Purdue.Extensions
{
    public static class ObservableCollectionExtensions
    {
        /// <summary>
        /// Move items inside the collection
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="self"></param>
        /// <param name="list">list items have to be members of collection</param>
        /// <param name="insertPosition"></param>
        public static void Move<T>(this ObservableCollection<T> self, IList list, int insertPosition)
        {
            if (self == null)
                throw new ArgumentNullException("self");

            if (list == null)
                throw new ArgumentNullException("list");

            if (insertPosition < 0)
                throw new ArgumentOutOfRangeException("insertPosition");

            var position = insertPosition;

            foreach (var item in list)
            {
                if (!(item is T))
                    throw new ArgumentException("list item has invalid type", "list");

                var itemIndex = self.IndexOf((T)item);

                if (itemIndex < 0)
                    throw new ArgumentException("list item not found", "list");

                if (itemIndex < (position - 1))
                {
                    self.Move(itemIndex, position - 1);
                }
                else if (itemIndex > position)
                {
                    self.Move(itemIndex, position);
                    position++;
                }
            }
        }
    }
}
